package se.cefalo.ceti.ical.ical4j;

import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.property.DateProperty;
import se.cefalo.ceti.ical.ICalService;

import java.io.Reader;
import java.util.Collection;
import java.util.HashSet;

/**
 * Created by IntelliJ IDEA.
 * User: kopo700
 * Date: Oct 30, 2006
 * Time: 3:52:34 PM
 * To change this template use File | Settings | File Templates.
 */
public class ICalServiceImpl implements ICalService {
    protected Calendar calendar;


    public void setIcalDB(Reader icalDB) {
        CalendarBuilder builder = new CalendarBuilder();
        try {
            calendar = builder.build(icalDB);
        } catch (Exception e) {
            throw new RuntimeException("Unable to parse given ical db", e);
        }
    }

    public Collection getDistinctNames() {
        HashSet set = new HashSet();
        ComponentList componentList = calendar.getComponents(Component.VEVENT);
        for (java.util.Iterator it = componentList.iterator(); it.hasNext();) {
            Object aComponentList = (Object) it.next();
            Component event = (Component) aComponentList;
            set.add(getEventName(event));
        }

        return set;
    }


    public long getTimeReported(String name) {
        long time = 0;
        ComponentList componentList = calendar.getComponents(Component.VEVENT);
        for (java.util.Iterator it = componentList.iterator(); it.hasNext();) {
            Object aComponentList = (Object) it.next();
            Component event = (Component) aComponentList;
            if (name.equals(getEventName(event))) {
                long start = getTime(event, Property.DTSTART);
                long end = getTime(event, Property.DTEND);

                time = time + end - start;
            }
        }
        return time;
    }

    private long getTime(Component event, String propertyName) {
        DateProperty end = (DateProperty) event.getProperty(propertyName);

        return end.getDate().getTime();
    }

    private String getEventName(Component event) {
        return event.getProperty(Property.SUMMARY).getValue();
    }
}
